<template>
  <div>
    <!-- 面包屑导航栏 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <el-card shadow="always" :body-style="{ padding: '20px' }">
      <!-- 添加角色按钮 -->
      <el-row class="addBtnRow">
        <el-button type="primary" @click="showAddRoleDialog">添加角色</el-button>
      </el-row>

      <!-- 角色列表 -->
      <el-table :data="rolesList" style="width: 100%" stripe border row-key="id">
        <el-table-column type="expand">
          <template slot-scope="scope">
            <!-- 一级权限 -->
            <!-- 这里本来是可以用三元表达式绑定样式类的 -->
            <el-row :gutter="15" v-for="item in scope.row.children" :key="item.id" type="flex">
              <el-col :span="6" :offset="0">
                <el-tag closable @close="showTipTag(item.id, scope.row.id)">{{ item.authName }}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <el-col :span="18" :offset="0">
                <el-row :gutter="15" v-for="item1 in item.children" :key="item1.id" class="rowSon" type="flex">
                  <el-col :span="6" :offset="0">
                    <el-tag closable type="success" @close="showTipTag(item1.id, scope.row.id)">{{ item1.authName }}</el-tag
                    ><i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18" :offset="0">
                    <el-tag closable type="warning" v-for="item2 in item1.children" :key="item2.id" @close="showTipTag(item2.id, scope.row.id)">{{ item2.authName }}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="roleName" label="角色名称"> </el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"> </el-table-column>
        <el-table-column label="操作" width="350">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" @click="showEditDialog(scope.row)">编辑</el-button>
            <el-button type="danger" icon="el-icon-delete" @click="deleRole(scope.row)">删除</el-button>
            <el-button type="warning" icon="el-icon-setting" @click="ShowSetRightDialog(scope.row.id)">分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 设置权限的对话框 -->
    <el-dialog title="分配权限" :visible.sync="setRigthDialogVisible" width="50%" @close="resetKey">
      <el-tree :data="rightTree" show-checkbox node-key="id" :default-checked-keys="defKeys" :props="rightProps" default-expand-all :indent="20" ref="treeIdRef"> </el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRigthDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRight">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 添加角色的对话框 -->
    <el-dialog title="添加角色" :visible.sync="addRoleDialogVisible" width="50%" @close="resetRoleForm">
      <el-form ref="addRoleForm" :model="addRoleForm" label-width="80px" :rules="addRoleRules">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model.trim="addRoleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input type="textarea" v-model="addRoleForm.roleDesc" rows="5" resize="none"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="queryAddRole">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑角色的对话框 -->
    <el-dialog title="添加角色" :visible.sync="editRoleDialogVisible" width="50%">
      <el-form ref="editRoleForm" :model="editRoleForm" label-width="80px" :rules="addRoleRules">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model.trim="editRoleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input type="textarea" v-model="editRoleForm.roleDesc" rows="5" resize="none"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="queryEditRole">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 角色列表数据
      rolesList: [],
      // 控制设置权限的对话框
      setRigthDialogVisible: false,
      // 权限树数据保存
      rightTree: [],
      // 权限树配置
      rightProps: {
        children: 'children',
        label: 'authName'
      },
      // 默认选择的节点id值数组
      defKeys: [],
      // 获取分配角色的id
      roleId: '',
      // 添加角色对话框开关
      addRoleDialogVisible: false,
      // 添加角色表单对象
      addRoleForm: {
        roleName: '',
        roleDesc: ''
      },
      // 添加角色表单校验规则
      addRoleRules: {
        roleName: [
          { required: true, message: '请输入用户名称', trigger: 'blur' },
          { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
        ]
      },
      // 编辑角色对话框开关
      editRoleDialogVisible: false,
      // 编辑角色的表单
      editRoleForm: {
        roleName: '',
        roleDesc: ''
      }
    }
  },
  methods: {
    // 获取角色数据列表
    async getRolesList() {
      const res = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.rolesList = res.data
    },

    // 实现删除权限功能
    async showTipTag(roleid, id) {
      const res = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (res === 'cancel') {
        return this.$message('已取消删除')
      }
      const resq = await this.$http.delete(`roles/${id}/rights/${roleid}`)
      const index = this.rolesList.findIndex(function(item) {
        return item.id === id
      })
      if (resq.meta.status !== 200) {
        return this.$message.error(resq.meta.msg)
      }
      this.$message.success(resq.meta.msg)
      this.rolesList[index].children = resq.data
    },

    // 实现设置权限messageBOX
    async ShowSetRightDialog(id) {
      // 将分配id保存如data中
      this.roleId = id
      // 获取所有权限的数据
      const res = await this.$http.get('rights/' + 'tree ')
      if (res.meta.status !== 200) {
        return this.$message.error('权限树请求失败')
      }
      this.rightTree = res.data
      // 根据id查询角色对应的index
      const index = this.rolesList.findIndex(item => {
        return item.id === id
      })
      // 可以优化通过scrop.row直接传入对应的角色
      this.getThreeId(this.rolesList[index], this.defKeys)
      this.setRigthDialogVisible = true
    },

    // 得到三级节点的id给展开列表利用递归函数
    getThreeId(node, arr) {
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(ele => {
        this.getThreeId(ele, arr)
      })
    },

    // 重置defKeys
    resetKey() {
      this.defKeys = []
    },

    // 发起提交权限id
    async allotRight() {
      const keys = [...this.$refs.treeIdRef.getCheckedKeys(), ...this.$refs.treeIdRef.getHalfCheckedNodes()]
      const idStr = keys.join(',')
      const res = await this.$http.post(`roles/${this.roleId}/rights`, {
        rids: idStr
      })
      if (res.meta.status !== 200) {
        return this.$message.error('更新失败')
      }
      this.$message.success('更新成功')
      this.setRigthDialogVisible = false
      this.getRolesList()
    },

    // 添加角色对话框控制按钮
    showAddRoleDialog() {
      this.addRoleDialogVisible = true
    },
    // 实现添加角色的功能
    queryAddRole() {
      this.$refs.addRoleForm.validate(async valid => {
        if (!valid) {
          return this.$message.error('表单验证失败')
        }
        // 发起添加请求
        this.addRoleForm.roleDesc.trim()
        const res = await this.$http.post('roles', this.addRoleForm)
        if (res.meta.status !== 201) {
          return this.$message.error(res.meta.msg)
        }
        this.$message.success(res.meta.msg)
        this.getRolesList()
        this.addRoleDialogVisible = false
      })
    },
    // 重置添加角色表单
    resetRoleForm() {
      this.addRoleForm = {
        roleName: '',
        roleDesc: ''
      }
    },

    // 编辑角色对话框控制按钮
    showEditDialog(role) {
      this.editRoleForm.roleName = role.roleName
      this.editRoleForm.roleDesc = role.roleDesc
      this.editRoleDialogVisible = true
    },
    // 实现编辑角色的功能
    queryEditRole() {
      this.$refs.editRoleForm.validate(async valid => {
        if (!valid) {
          return this.$message.error('表单验证失败')
        }
        // 发起更新角色信息的请求
        const res = await this.$http.put('roles/' + this.editRoleForm.id, this.editRoleForm)
        if (res.meta.status !== 200) {
          return this.$message.error(res.meta.msg)
        }
        this.$message.success(res.meta.msg)
        this.editRoleDialogVisible = false
      })
    },

    // 实现删除角色功能
    async deleRole(role) {
      const val = await this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (val === 'cancel') {
        return this.$message('已取消删除')
      }
      // 删除角色
      const res = await this.$http.delete('roles/' + role.id)
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.$message.success(res.meta.msg)
      this.getRolesList()
    }
  },
  mounted() {
    this.getRolesList()
  }
}
</script>

<style lang="less" scoped>
.addBtnRow {
  margin-bottom: 15px;
  border: 0 !important;
}

.el-tag {
  font-size: 16px;
  margin: 10px 20px;
}

.el-row {
  border-top: 1px solid #eef1ee;
  border-bottom: 1px solid #eef1ee;
  align-items: center;
  margin-top: -1px;
}

.rowSon {
  margin-bottom: -1px;
  border-top: 0;
}
</style>
